package org.example.pcbcircuitboard.config;

import org.eclipse.paho.client.mqttv3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;

import java.io.Serializable;

@Configuration
public class MqttConfig implements Serializable {
    @Autowired
    private MqttCallback mqttCallback;
    @Value("${mqtt.url}")
    private String url;
    @Value("${mqtt.username}")
    private String username;
    @Value("${mqtt.password}")
    private String password;
    @Value("${mqtt.client-id}")
    private String clientId;
    @Value("${mqtt.topic}")
    private String topic;

    /**
     * 创建连接
     * @return mqtt客户端连接
     */
    @Bean
    public IMqttClient iMqttClient() throws MqttException {
        MqttConnectOptions options=new MqttConnectOptions();
        options.setUserName(username);
        options.setPassword(password.toCharArray());
        // 设置为true 表示每一次连接都会以新的身份认证
        options.setCleanSession(false);
        // 超时时间/秒
        options.setConnectionTimeout(30);
        // 心跳/秒
        options.setKeepAliveInterval(10);
        // 开启自动重新连接
        options.setAutomaticReconnect(true);
        // 设置重连等待时间/秒
        options.setMaxReconnectDelay(5000);
        // 设置遗嘱消息 提醒客户端连接已经意外断开
        options.setWill("willTopic",("Error:连接意外断开！！！").getBytes(),0,false);
        // 创建客户端实例
        DefaultMqttPahoClientFactory factory=new DefaultMqttPahoClientFactory();
        IMqttClient mqttClient=factory.getClientInstance(url,clientId);
        // 设置回调
        mqttClient.setCallback(mqttCallback);
        mqttClient.connect(options);
        // TODO 订阅主题
        String[] topics={topic,"pcb/control"};
        int[] qos={0,1};
        mqttClient.subscribe(topic,0);
        return mqttClient;
    }
}
